#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import	os, os.path

import	md5
import	tempfile

import	unittest
import	zxstore.store as store

from	zxstore import KeyDupError,  KeyNotFoundError


class	TestStore(unittest.TestCase) :

	def	map(self, key) :
		m = md5.new()
		m.update(key)
		digest = m.hexdigest()
		x = digest[:1]
		return int(x, 16)

	def	setUp(self) :
		tmpdir = tempfile.gettempdir()
		if tmpdir is None :
			raise RuntimeError, 'invalid tmpdir'
		store_path = tmpdir + os.sep + 'storem' + os.sep + 'store'
		if os.path.isdir(store_path) :
			import	glob
			files = glob.glob(store_path + os.sep + '*' + os.sep + '*.*')
			for file in files :
				os.remove(file)
		else :
			os.makedirs(store_path, 0777)
		self.storer = store.Store(store_path, self.map)

	def	tearDown(self) :
		self.storer = None

	def	testInsert(self) :
		key = 'key0001'
		value = 'value0001'
		self.storer.insert(key, value)
		v = self.storer.find(key)
		self.assertEqual(value, v, 'FIND after INSERT key "%s" : expect "%s", but return "%s" ' % (key, value, v))
		self.assertRaises(KeyDupError, self.storer.insert, key, value)

		key = 'key0002'
		value = 'value0002'
		self.assertRaises(KeyNotFoundError, self.storer.update, key, value)
		self.storer.insert(key, value)
		v = self.storer.find(key)
		self.assertEqual(value, v, 'FIND after INSERT key "%s" : expect "%s", but return "%s" ' % (key, value, v))
		self.assertRaises(KeyDupError, self.storer.insert, key, value)

		value = 'value0002UPDATE'
		self.storer.update(key, value)
		v = self.storer.find(key)
		self.assertEqual(value, v, 'FIND after UPDATE key "%s" : expect "%s", but return "%s" ' % (key, value, v))

		# delete key0002
		self.storer.erase(key)
		self.assertRaises(KeyNotFoundError, self.storer.erase, key)
		self.assertRaises(KeyNotFoundError, self.storer.find, key)

		# delete key0001
		key = 'key0001'
		self.storer.erase(key)
		self.assertRaises(KeyNotFoundError, self.storer.erase, key)
		self.assertRaises(KeyNotFoundError, self.storer.find, key)


	# class TestStore

if	__name__ == '__main__' :
	unittest.main()
